package services

import (
	"chat/models"
	"chat/pkg/utils"
)

// MessageService 消息服务
type MessageService struct{}

// SendMessage 发送消息
func (s *MessageService) SendMessage(fromUserID uint, content string, msgType int) error {
	message := models.Message{
		FromUserID: fromUserID,
		Content:    content,
		Type:       msgType,
	}
	return utils.DB.Create(&message).Error
}

// MessageWithUser 包含发送者信息的消息
type MessageWithUser struct {
	models.Message
	SenderName string `json:"sender_name"` // 发送者昵称或用户名
}

// GetMessages 获取历史消息
func (s *MessageService) GetMessages(limit, offset int) ([]MessageWithUser, error) {
	var messages []MessageWithUser
	err := utils.DB.Model(&models.Message{}).
		Select("messages.*, COALESCE(users.nickname, users.username) as sender_name").
		Joins("LEFT JOIN users ON messages.from_user_id = users.id").
		Order("messages.created_at desc").
		Limit(limit).
		Offset(offset).
		Find(&messages).Error
	return messages, err
}

// MarkMessageAsRead 将消息标记为已读
func (s *MessageService) MarkMessageAsRead(messageID uint) error {
	return utils.DB.Model(&models.Message{}).Where("id = ?", messageID).Update("status", 2).Error
}

// GetUnreadMessages 获取未读消息
func (s *MessageService) GetUnreadMessages(userID uint) ([]models.Message, error) {
	var messages []models.Message
	err := utils.DB.Where("to_user_id = ? AND status = ?", userID, 1).Find(&messages).Error
	return messages, err
}

// DeleteMessage 删除消息
func (s *MessageService) DeleteMessage(messageID, userID uint) error {
	return utils.DB.Where("id = ? AND (from_user_id = ? OR to_user_id = ?)",
		messageID, userID, userID).Delete(&models.Message{}).Error
}
